<template>
  <div class="detaBox">
    <div class="content bgfff">
      <div class="container">
        <el-button  class="BtnDocking" @click="Goup">返回</el-button>
        <div class="title_box">
          <div class="title">{{ data.detail.title }}</div>
          <div class="time">
            <div class="newtime">
              发布时间 ：{{ getLocalTime(data.detail.addtime, "yyyy-mm-dd") }}
            </div>
          </div>
          <!-- <el-button
            class="BtnDocking customStyle"
            :disabled="true"
            @click="handleIsRegister"
            v-if="
              (data.detail.demand_status === '3' || data.detail.demand_status === '5') &&
              data.detail.solve_user_id !== data.userid
            "
          >
            该需求已解决/已过期
          </el-button>
          <el-button
            class="BtnDocking customStyle"
            :disabled="true"
            @click="handleIsRegister"
            v-else-if="
              data.detail.demand_status === '3' &&
              data.detail.solve_user_id === data.userid
            "
          >
            该需求已由您解决
          </el-button>
          <el-button
            class="BtnDocking customStyle"
            :disabled="true"
            v-else-if="
              data.detail.demand_status == '4' && data.detail.user_id === data.userid
            "
          >
            您的需求审核未通过
          </el-button> -->
          <div>
            <el-button
              v-if="
                data.detail.demand_status === '0' && data.detail.user_id === data.userid
              "
              :class="
                !(
                  data.detail.demand_status === '0' && data.detail.user_id === data.userid
                )
                  ? 'demand_docking'
                  : 'width100'
              "
              type="primary"
            >
              您的需求正在审核
            </el-button>
            <el-button v-else class="BtnDocking" @click="handleIsRegister">{{
              data.detail.is_docking == 1 ? "立即留言" : "立即对接"
            }}</el-button>
          </div>
        </div>

        <el-breadcrumb class="breadcrumd">
          <el-breadcrumb-item :to="{ path: '/About' }">供需对接</el-breadcrumb-item>
          <el-breadcrumb-item>供需详情</el-breadcrumb-item>
        </el-breadcrumb>

        <div class="TextBox">
          <div class="title">需求详情：</div>
          <div class="text" v-html="data.detail.describe"></div>
          <div>
            <el-image
              style="width: 156px; height: 158px"
              :src="item"
              fit="cover"
              v-for="item in data.detail.img"
              @click="describeImg(item)"
              :key="item"
            />
          </div>
          <div
            v-if="
              !data.isList &&
              data.detailList.is_docking == '1' &&
              data.detailList.demand_status === '1'
            "
            style="margin-top: 15px"
          >
            <div
              v-if="
                data.detailList.is_own == 1 &&
                data.detailList.demand_status == '1' &&
                handleGetUserId()
              "
            >
              <el-button
                style="background-color: #1562ca; color: #fff"
                @click.stop="handleGoEdit(data.detailList.id)"
                >修改</el-button
              >
              <el-button
                @click="handleOpenEnd(data.detailList.id)"
                style="background-color: #c0021a; color: #fff"
                >结束</el-button
              >
            </div>
          </div>
        </div>
        <div
          class="Publisher"
          v-if="
            !data.isList &&
            data.detail.is_own == 0 &&
            data.detail.is_docking == '1' &&
            handleGetUserId()
          "
        >
          <div>
            <div class="title">发布人：</div>
            <div class="detail" v-for="items in data.contactsLists" :key="items.id">
              <div class="imgBox">
                <el-image :src="items.head_img" fit="cover" />
              </div>
              <div class="textBox">
                <div class="name">{{ items.name }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- <div
          class="Docking"
          v-if="
            data.chatList.records && data.chatList.records.length > 0 && handleGetUserId()
          "
        >
          <div class="title">对接详情:</div>
          <div
            class="detail"
            v-for="(items, index) in data.chatList.records"
            :key="index"
          >
            <div class="imgBox">
              <el-image :src="items.head_img" fit="cover" />
            </div>
            <div class="textBox">
              <div class="name">{{ items.username }}</div>
              <div class="text">{{ items.content }}</div>
              <div class="time">
                <span>{{ items.datetime }}</span>
                <span
                  style="color: #cb061e; margin-left: 20px; cursor: pointer"
                  @click="handleLeaveMessage(items.record_id)"
                  >回复<el-icon style="vertical-align: bottom">
                    <ChatLineSquare /> </el-icon
                ></span>
              </div>

              <div
                v-for="(chilItem, chiIndex) in items.records_child"
                :key="chiIndex"
                class="list_shadow"
              >
                <div class="u-flex">
                  <el-image :src="chilItem.head_img" fit="contain" />
                  <div class="u-m-l-20">
                    <div style="margin-bottom: 10px">
                      <span class="font_weight_bold">{{ chilItem.username }}</span>
                    </div>
                    <span class="text">{{ chilItem.content }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div> -->
      </div>
    </div>

    <el-dialog v-model="data.showInputPopup" title="联系方式" width="325px">
      <span class="secondTitle" @click="callPhone(data.detail.phone)">{{
        data.detail.phone
      }}</span>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { defineAsyncComponent, ref, reactive, watch } from "vue";
// import { ArrowRight, ChatLineSquare, Plus, Delete } from "@element-plus/icons";
import {
  getDemandDetail,
  getDemandChat,
  demendSendText,
  getDemandNameById,
  solveDemand,
  demandComplaint,
} from "@/network/apiKaiqiton";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
// import { debounce } from "@/utils/index";

const router = useRouter();
const route = useRoute();
const address: any = ref([]);
const data = reactive({
  id: route.query.id,
  uploadHeader: {
    authorization: sessionStorage.getItem("token"),
  },
  action: "https://test.tianji.unspace.cn/cgi/api/upload_image",
  userid: sessionStorage.getItem("user_id"),
  chatList: {} as any,
  detail: {} as any,
  detailList: [] as any,
  demandOrSupply: "demand",
  dialogImageUrl: "",
  demandTypeObj: {
    demand: "需求",
  } as any,
  contactsLists: [] as any,
  isList: false,
  disabled: false,
  dialogVisible: false,
  showInputPopup: false,
  inputFocus: false,
  sendText: "",
  pid: 0,
  demandId: "",
  showEndModal: false,
  innerVisible: false,
  lists: [] as any,
  radio1: "0",
  complaintShow: false,
  tipsList: [
    {
      name: "电话虚假（空号/无人接听）",
      id: "1",
    },
    {
      name: "涉黄违法",
      id: "2",
    },
    {
      name: "虚假信息（虚构采购需求、不实供应信息等）",
      id: "3",
    },
    {
      name: "恶意营销",
      id: "4",
    },
    {
      name: "分类错误",
      id: "5",
    },
  ],
  tipsListId: [] as any,
  tipsListName: [] as any,
  content: "",
  imgList: [] as any,
});
const Goup = () => {
  router.go(-1)
}
const callPhone = (phone: any) => {
  window.location.href = "tel://" + Number(phone);
};
const handleGetDetail = (id: any) => {
  getDemandDetail({
    id,
    uid: data.userid,
  }).then((res1: any) => {
    let res = res1.data;
    handleGetChatList();
    data.detailList = {
      demandOrSupply: data.demandOrSupply,
      resetName: data.demandTypeObj[`${data.demandOrSupply}`],
      ...res,
      type_name: res.typename,
    };
    data.detail = res;
    const {
      // eslint-disable-next-line camelcase
      user_type,
      // eslint-disable-next-line camelcase
      user_position,
      // eslint-disable-next-line camelcase
      user_mobile,
      // eslint-disable-next-line camelcase
      user_name,
      // eslint-disable-next-line camelcase
      user_id,
      // eslint-disable-next-line camelcase
      user_head_img,
      address,
      industryname,
    } = res;
    data.contactsLists = [
      {
        id: user_id,
        type: user_type,
        head_img: user_head_img,
        name: user_name,
        position: user_position,
        address,
        mobile: user_mobile,
        isf: res.is_friend,
        industry_names: [industryname],
      },
    ];
  });
};
const handleGoComplain = () => {
  if (!sessionStorage.getItem("user_id")) {
    ElMessage.error("请点击对接后进行投诉");
    return;
  }
  data.complaintShow = true;
};
const successImg = (response: any, uploadFile: any, uploadFiles: any) => {
  const demo = {
    name: uploadFile.name,
    url: response.data.url,
  };
  data.imgList.push(demo);
};
const exceedImg = (file: any) => {
  ElMessage({
    showClose: true,
    message: "最多只能上传四张图片",
    type: "warning",
  });
};
const handlePictureCardPreview = (file: any) => {
  data.dialogImageUrl = file.url!;
  data.dialogVisible = true;
};
const describeImg = (file: any) => {
  data.dialogVisible = true;
  data.dialogImageUrl = file;
};
const removeImg = (uploadFile: any) => {
  // eslint-disable-next-line array-callback-return
  data.imgList.map((res: any, index: any) => {
    if (res.url === uploadFile.url) {
      data.imgList.splice(index, 1);
    }
  });
};
// const getLocalTime = (nS: any) => {
//   const date = new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/, ' ')
//   // 截取data前面两个字符
//   const returnDate = date.substring(0, 9)
//   return returnDate
// }
const getLocalTime = (dateTime: any = null, fmt = "yyyy-mm-dd") => {
  // 如果为null,则格式化当前时间
  if (!dateTime) dateTime = Number(new Date());
  // 如果dateTime长度为10或者13，则为秒和毫秒的时间戳，如果超过13位，则为其他的时间格式
  if (dateTime.toString().length === 10) dateTime *= 1000;
  const date = new Date(dateTime);
  let ret;
  const opt = {
    "y+": date.getFullYear().toString(), // 年
    "m+": (date.getMonth() + 1).toString(), // 月
    "d+": date.getDate().toString(), // 日
    "h+": date.getHours().toString(), // 时
    "M+": date.getMinutes().toString(), // 分
    "s+": date.getSeconds().toString(), // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  } as any;
  for (const k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt);
    if (ret) {
      fmt = fmt.replace(
        ret[1],
        ret[1].length === 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
      );
    }
  }
  return fmt;
};
const handleGetChatList = () => {
  const param = {
    user_id: data.userid || "49",
    demand_id: data.id,
    order: "asc",
  };
  getDemandChat(param).then((res) => {
    data.chatList = {
      ...res.data,
      is_docking: data.detail.is_docking,
      demand_status: data.detail.demand_status,
    };
  });
};
const handleGoEnd = () => {
  data.innerVisible = true;
  getDemandNameById({
    id: data.id,
  }).then((res: any) => {
    data.lists = res.data;
  });
};
const activeTag = (item: any) => {
  if (data.tipsListId.includes(item.id)) {
    data.tipsListId.splice(data.tipsListId.indexOf(item.id), 1);
    data.tipsListName.splice(data.tipsListName.indexOf(item.name), 1);
  } else {
    data.tipsListId.push(item.id);
    data.tipsListName.push(item.name);
  }
};
const handleSubmit = () => {
  solveDemand({
    channel_id: 4,
    demand_id: data.demandId,
  }).then((res) => {
    ElMessage({
      showClose: true,
      message: "需求已解决",
    });
    data.innerVisible = false;
    data.showEndModal = false;
    router.push({
      path: "/index",
    });
  });
};
const handleIsRegister = () => {
  console.log(data.showInputPopup, "data.showInputPopup");

  if (!sessionStorage.getItem("token")) {
    ElMessage({
      message: "请先登录",
      type: "warning",
    });
  } else {
    data.showInputPopup = true;
    console.log(data.showInputPopup, "data.showInputPopup");
  }
};
const confirm = () => {
  const imgs = data.imgList.map((item: any) => {
    return item.url;
  });
  const tagName = data.tipsListName.join(",");
  const param = {
    uid: data.userid,
    demand_id: data.id,
    img: imgs.join(","), // 图片
    note: data.content,
    content: tagName,
  };
  console.log("param", param);
  demandComplaint(param).then((res) => {
    ElMessage({
      showClose: true,
      message: "投诉成功",
    });
    data.tipsListId = [];
    data.tipsListName = [];
    data.content = "";
    data.imgList = [];
    data.complaintShow = false;
  });
};
const handleGetUserId = () => {
  return data.userid;
};
const handleSendText = () => {
  const param = {
    user_id: data.userid,
    demand_id: data.id,
    content: data.sendText,
    pid: data.pid,
  };
  demendSendText(param).then((res: any) => {
    handleGetDetail(data.id);
    data.showInputPopup = false;
    handleGetChatList();
    data.sendText = "";
  });
};
const handleGoEdit = (id: any) => {
  console.log(id, "id");
  router.push({
    path: "/releaseDemand",
    query: {
      id,
    },
  });
};
const handleOpenEnd = (id: any) => {
  data.demandId = id;
  data.showEndModal = true;
};
const handleLeaveMessage = (pid: any) => {
  data.pid = pid;
  data.showInputPopup = true;
};

const debounce = (
  func: { apply: (arg0: any, arg1: any[]) => void },
  time: number | undefined,
  ctx?: any,
  immediate?: any
) => {
  // eslint-disable-next-line no-undef
  let timer: any;
  const rtn = (...params: any[]) => {
    clearTimeout(timer);
    if (immediate) {
      const callNow = !timer;
      timer = setTimeout(() => {
        timer = null;
      }, time);
      if (callNow) func.apply(ctx, params);
    } else {
      timer = setTimeout(() => {
        func.apply(ctx, params);
      }, time);
    }
  };
  return rtn;
};
// eslint-disable-next-line camelcase
const handleSendText_debounce = debounce(handleSendText, 2000);

watch(
  () => router.currentRoute.value.query.id,
  (val) => {
    data.detail = {};
    handleGetDetail(val);
  },
  { immediate: true }
);
</script>

<style lang="scss" scoped>
.detaBox {
  padding: 40px 0 50px 0;
}
.content {
  margin: 0 auto;
  padding: 30px 30px;
  box-shadow: 0px 0px 14px 4px rgba(205, 213, 232, 0.31);
}
.title_box {
  margin-top: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e9e9e9;
  position: relative;

  .title {
    font-size: 34px;
  }

  .time {
    margin-top: 30px;
    display: flex;

    .demand {
      margin-left: 80px;
    }
  }

  .BtnDocking {
    position: absolute;
    background-color: #1562ca;
    color: #fff;
    top: 50%;
    right: 0;
    transform: translateY(-50%);
    min-width: 140px;
    height: 50px;
  }

  .customStyle {
    background-color: #97999b;
  }

  .btnCustomStyle {
    border: "none";
  }
}

.breadcrumd {
  margin: 15px 0;
  font-size: 16px;
}

.TextBox {
  padding-bottom: 15px;
  border-bottom: 1px solid #e9e9e9;

  .title {
    font-size: 20px;
    font-weight: 500;
    color: #000000;
    margin: 20px 0;
  }

  .text {
    font-size: 17px;
    font-weight: 300;
    color: #000000;
    margin: 20px 0;
  }

  .el-image {
    margin: 0 15px 0 0;
  }
}

.Publisher {
  padding: 15px 0;
  border-bottom: 1px solid #e9e9e9;

  .title {
    font-size: 20px;
    font-weight: 500;
    color: #000000;
    margin-bottom: 20px;
  }

  .detail {
    display: flex;

    .imgBox {
      border-radius: 50%;
      width: 56px;
      overflow: hidden;
      height: 58px;
      margin-right: 10px;

      .el-image {
        width: 100%;
        height: 100%;
      }
    }

    .textBox {
      font-size: 14px;

      .name {
        font-size: 24px;
        line-height: 58px;
      }

      .text {
        font-size: 12px;
        color: #b4b4b4;
        margin: 10px 0;
      }

      ::v-deep .tagBox {
        .el-tag {
          height: 20px;
          line-height: 19px;
          padding: 0 5px;
        }
      }
    }
  }
}

.Docking {
  .title {
    font-size: 20px;
    font-weight: 500;
    color: #000000;
    margin: 31px 0 21px 0;
  }

  .detail {
    display: flex;
    padding: 20px 0;
    border-bottom: 1px solid #e9e9e9;

    .imgBox {
      border-radius: 50%;
      width: 56px;
      overflow: hidden;
      height: 58px;
      margin-right: 10px;

      .el-image {
        width: 100%;
        height: 100%;
      }
    }

    .textBox {
      font-size: 14px;

      .name {
        color: #5a5761;
        margin-bottom: 30px;
      }

      .text {
        color: #a9a5b2;
        margin-bottom: 30px;
      }

      .time {
        color: #dddddd;
      }

      .list_shadow {
        box-shadow: 0px 5px 23px 3px rgba(153, 153, 153, 0.24);
        border-radius: 5px !important;
        padding-right: 32px !important;
        padding-bottom: 15px !important;
        padding-top: 14px !important;
        padding-left: 28px !important;
        box-sizing: border-box;
        margin-top: 20px !important;

        .u-flex {
          display: flex;
          flex-direction: row;
          align-items: center;

          .el-image {
            width: 35px;
            height: 35px;
            border-radius: 50%;
            overflow: hidden;
          }

          .u-m-l-20 {
            margin-left: 20px !important;

            .font_weight_bold {
              color: #5a5761;
              margin-bottom: 30px;
            }

            .text {
              color: #a9a5b2;
              margin-bottom: 30px;
            }
          }
        }
      }
    }
  }
}

.complain_operate_circle {
  background-color: #cb061e;
  box-shadow: 0px 5px 9px 2px rgba(213, 8, 33, 0.3);
  border-radius: 50%;
  position: fixed;
  z-index: 2;
  width: 48px;
  height: 48px;
  justify-content: center;
  display: flex;
  flex-direction: row;
  align-items: center;
  box-sizing: border-box;
  right: 5%;
  bottom: 18%;
  color: #fff;
  cursor: pointer;

  .demand_complain {
  }
}

.list_shadow {
  .tagBox {
    margin-top: 20px;

    .tagitem {
      color: #666666ff;
      background-color: #edededff;
      border-color: #edededff;
      margin-bottom: 15px;
      margin-right: 15px;
      cursor: pointer;
    }

    .tagitem_active {
      color: #fff;
      background-color: #cb061e;
      border-color: #cb061e;
    }
  }
}

.uploadInput {
  margin: 20px 0;
}

.fontf849 {
  color: #f8494dff;
}

@media screen and (max-width: 768px) {
  .title_box {
    margin-top: 0;
    .BtnDocking {
      min-width: 90px !important;
      position: initial;
      transform: translateY(0);
      height: initial;
    }
    .title {
      font-size: 26px;
    }
    .time {
      margin: 20px 0;
    }
  }
}
</style>
